package cn.sakura.security.filter;

import cn.hutool.core.util.StrUtil;
import cn.sakura.api.moudle.admin.SysUserService;
import cn.sakura.common.domain.admin.entity.SysUser;
import cn.sakura.common.utils.JwtUtil;
import cn.sakura.security.handler.UserDetailServiceImpl;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt身份验证过滤器
 *
 * @author icatw
 * @date 2022/5/5
 * @email 762188827@qq.com
 * @apiNote
 */
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    UserDetailServiceImpl userDetailService;
    @Autowired
    SysUserService sysUserService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader(jwtUtil.getHeader());
        //jwt为空直接跳过
        String uri = request.getRequestURI();
        if (StrUtil.isBlankOrUndefined(token)||uri.equals("/captcha")) {
            chain.doFilter(request, response);
            return;
        }
        Claims claim = jwtUtil.getClaimByToken(token);
        if (claim == null) {
            request.setAttribute("errorMessage","token异常");
            throw new JwtException("token 异常");
        }
        if (jwtUtil.isTokenExpired(claim)) {
            request.setAttribute("errorMessage","token过期，请重新登陆");
            throw new JwtException("token过期，请重新登陆");
        }
        //String username = claim.getSubject();
        String username = (String) claim.get("username");
        // 获取用户的权限等信息

        SysUser sysUser = sysUserService.getByUsername(username);
        UsernamePasswordAuthenticationToken user
                = new UsernamePasswordAuthenticationToken(username, null,
                userDetailService.getUserAuthority(sysUser.getId()));

        SecurityContextHolder.getContext().setAuthentication(user);

        chain.doFilter(request, response);
    }
}
